import PropTypes from 'react-router/lib/PropTypes'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'


 import * as LeaveMessageAction from '../../actions/leaveMessage'

 import ViewLeaveMessage from '../data/ViewLeaveMessage'

import { WeaErrorPage, WeaTools,WeaTextarea ,WeaBrowser,WeaSelect,WeaNewScroll  } from 'ecCom'
import {Button,Select,Icon,Form, Input,Modal,Spin,Row,Col} from "antd";
const Option = Select.Option;
const FormItem = Form.Item;
const createForm = Form.create;

import Immutable from 'immutable'
const is = Immutable.is;
import equal from 'deep-equal'

class LeaveMessage extends React.Component {
	constructor(props) {
		super(props);
        this.state={
            direction:"down",
            ascSort:true,
            selectedValue:"1",
            orderway:0
        }
	}
	componentWillMount() {
        const { actions,params,location } = this.props;
        let fromUrl = {}; 
        if(location && JSON.stringify(location.query)!=="{}"){
            fromUrl = location.query;  
        } 
        const newBaseParams = {...params,...fromUrl,...{from:"mine"}};
        actions.initDatas(newBaseParams);
	}
	componentWillReceiveProps(nextProps) {
        const oldParams = this.props.params;
        const newParams = nextProps.params;
        if(!equal(oldParams,newParams)){
            const { actions,params } =nextProps;
            actions.initDatas(params);
        }
	}
	shouldComponentUpdate(nextProps, nextState) {
		return !is(this.props.loading,nextProps.loading)||
        !is(this.props.params,nextProps.params)||
        !is(this.props.viewMessages,nextProps.viewMessages)||
        !is(this.state.ascSort,nextState.ascSort)||
        !is(this.state.direction,nextState.direction)||
        !is(this.props.messageFields,nextProps.messageFields)||
        !is(this.props.rowHeight,nextProps.rowHeight)||
        !is(this.props.customerId,nextProps.customerId);
	}

	componentWillUnmount() {
		//组件卸载时一般清理一些状态

	}
	render() {
		const { loading, title,customerId,viewMessages ,rowHeight} = this.props;
        const {direction,value,ascSort,selectedValue} = this.state;
        const {getFieldProps} = this.props.form;
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 16 },
        };
		return (
			<div className="customer-contact">
                <div >
                    <Form horizontal >
                        <Row >
                            <Col span="24" style={{marginBottom:"5px"}}>
                                <Input type="textarea" {...getFieldProps("ContactInfo", {
                                    initialValue:""})} placeholder="请填写留言信息" rows={rowHeight} onFocus={this.textOnFocus} />
                            </Col>
                        </Row>
                        <Row className="customer-contact-header" style={{display:rowHeight == "1" ? "none":"block"}}>
                            <Col span="24" >
                                <Button type="primary" size="small" onClick={this.submitMessage}>提交</Button>
                                <span className="customer-contact-group-addition" style={{float:"right"}}><span style={{marginRight:5}} onClick={this.showBrowsers}>附加信息</span><Icon type={direction} /></span>
                            </Col>
                        </Row>
                        <Row style={{display:direction == "down" ? "none":"block"}}>
                            <Col span="24" >
                                <FormItem
                                    label={"相关文档"}
                                    {...formItemLayout}>
                                    <WeaBrowser {...getFieldProps('relateddoc', { initialValue: '' })}  type={9} title="文档" hasAdvanceSerach={true} isSingle={false} />
                                </FormItem>
                            </Col>
                        </Row>
                    </Form>
                    <div className="customer-contact-bottomline"></div>
                </div>
                <div className="customer-contact-content">
                    <div className="customer-contact-sort">
                        <WeaSelect 
                            value={selectedValue}   
                            options={[{key: "1", selected: true, showname:"近一月"},
                                    {key: "2", selected: false, showname: "近三月"},
                                    {key: "3", selected: false, showname: "近半年"},
                                    {key: "4", selected: false, showname: "近一年"},
                                    {key: "0", selected: false, showname: "全部"}]} 
                            onChange={this.dateSelectChange.bind(this)}
                        />
                        <Spin spinning={loading} />
                        <div onClick={this.sortByAsc} className="customer-contact-sort-asc" style={{ background: `url(/spa/crm/images/icon_sequence_${ascSort ? "":"h_"}e9.png)`}}></div>
                        <div onClick={this.sortByDesc} className="customer-contact-sort-asc" style={{ background: `url(/spa/crm/images/icon_reverse_${ascSort ? "h_":""}e9.png)`}}></div>
                    </div>
                    <div id="viewMessages" style={{height:"100%",overflow: "auto"}}  onClick={this.textOnBlur}>
                         <WeaNewScroll height={"100%"} children={<ViewLeaveMessage data={viewMessages}/>} />
                    </div>
                </div>
            </div>
		)
    }
    textOnFocus=()=>{
        const {actions  } = this.props;
        actions.changeTextHeight(4);
    }
    textOnBlur=()=>{
        const {actions ,messageFields } = this.props;
        const value = messageFields.get('ContactInfo') && messageFields.get('ContactInfo').get('value') || "";
        if(!value){
             actions.changeTextHeight(1);
             this.setState({direction:"down"});
        }
    }
    showBrowsers=()=>{
        const {direction} = this.state;
        if(direction=="down"){
            this.setState({direction:"up"});
        }else{
            this.setState({direction:"down"});
        }
    }
    sortByDesc=()=>{
        const { actions,params,customerId } = this.props;
        const {selectedValue} = this.state;
         this.setState({ascSort:true,orderway:0});
        actions.initDatas({...params,...{orderway:0,customerId:customerId,selectedValue:selectedValue}});
    }
     sortByAsc=()=>{
        const { actions,params } = this.props;
        const {selectedValue} = this.state;
        this.setState({ascSort:false,orderway:1});
        actions.initDatas({...params,...{orderway:1,customerId:customerId,selectedValue:selectedValue}});
    }
    dateSelectChange=(value)=>{
        const { actions,params } = this.props;
        const {orderway} = this.state;
        this.setState({selectedValue:value});
        actions.initDatas({...params,...{orderway:orderway,customerId:customerId,selectedValue:value}});
    }
    submitMessage=()=>{
        const {params,actions,customerId,messageFields}  =this.props;
        const value = messageFields.get('ContactInfo') && messageFields.get('ContactInfo').get('value') || "";
        if(value){
            const content= {
                customerId:customerId ,
                ContactInfo:value,
                relateddoc:messageFields.get('relateddoc') && messageFields.get('relateddoc').get('value') || "",
            };
            actions.saveLeaveMessage(content);
             this.setState({direction:"down"});
        }else{
             Modal.info({
                title: '系统提示',
                content: '请填写联系记录！',
            });
        }
       
    }
    
}

//组件检错机制
class MyErrorHandler extends React.Component {
	render() {
		const hasErrorMsg = this.props.error && this.props.error !== "";
		return(
			<WeaErrorPage msg={ hasErrorMsg ? this.props.error : "对不起，该页面异常，请联系管理员！" } />
		);
	}
}

LeaveMessage = WeaTools.tryCatch( React, MyErrorHandler, { error: "" })(LeaveMessage);

//form 表单与 redux 双向绑定
LeaveMessage = createForm({
	onFieldsChange(props, fields) {
		props.actions.saveMessageFields({ ...props.messageFields.toJS(), ...fields });
	},
	mapPropsToFields(props) {
		return props.messageFields.toJS();
	}
})(LeaveMessage);


// 把 state map 到组件的 props 上
const mapStateToProps = state => {
	const { crmleaveMessage} = state;
	return { 
        loading: crmleaveMessage.get('loading'),
        viewMessages:crmleaveMessage.get('viewMessages'),
        messageFields:crmleaveMessage.get('messageFields'),
        rowHeight:crmleaveMessage.get('rowHeight'),
        customerId:crmleaveMessage.get('customerId')
    }
}

// 把 dispatch map 到组件的 props 上
const mapDispatchToProps = dispatch => {
	return {
		actions: bindActionCreators(LeaveMessageAction, dispatch)
	}
}

export default connect(mapStateToProps, mapDispatchToProps)(LeaveMessage);